#include "LoginWindow.hpp"
#include "RegisterWindow.hpp"
#include "UserChatWindow.hpp"
#include "UsersRegister.hpp"
#include "tools/Hash.hpp"
#include "tools/Logger.hpp"
#include <QApplication>
#include <QFormLayout>
#include <QGraphicsDropShadowEffect>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QPaintEvent>
#include <QPainter>
#include <QPainterPath>
#include <QPixmap>
#include <QScreen>
#include <QStyle>
#include <qdebug.h>



LoginWindow::LoginWindow(QWidget *parent)
    : QMainWindow(parent), isDragging(false) {
  // 加载背景图片
  backgroundImage.load(
      "/home/ccy/code_workspace/cpp_finall/resource/img/wave.png");

  setupUI();
  setupConnections();
  setWindowTitle("登录");
}

LoginWindow::~LoginWindow() {}

void LoginWindow::setupUI() {
  centralWidget = new QWidget(this);
  setCentralWidget(centralWidget);

  // 获取屏幕尺寸
  QScreen *screen = QGuiApplication::primaryScreen();
  QRect screenGeometry = screen->geometry();
  int screenWidth = screenGeometry.width();
  int screenHeight = screenGeometry.height();

  // 设置窗口大小为屏幕的40%
  int windowWidth = static_cast<int>(screenWidth * 0.6);
  int windowHeight = static_cast<int>(screenHeight * 0.6);
  resize(windowWidth, windowHeight);

  // 主布局使用QHBoxLayout，分为左右两部分
  QHBoxLayout *mainHLayout = new QHBoxLayout(centralWidget);
  mainHLayout->setContentsMargins(0, 0, 0, 0);
  mainHLayout->setSpacing(0);

  // 左边部分 - 装饰图
  QWidget *leftWidget = new QWidget(centralWidget);
  leftWidget->setFixedWidth(static_cast<int>(windowWidth * 0.45));
  QVBoxLayout *leftLayout = new QVBoxLayout(leftWidget);

  // 添加波浪背景
  QLabel *waveLabel = new QLabel(leftWidget);
  QPixmap wavePixmap(
      "/home/ccy/code_workspace/cpp_finall/resource/img/wave.png");
  waveLabel->setPixmap(wavePixmap.scaled(leftWidget->width(), windowHeight,
                                         Qt::KeepAspectRatioByExpanding,
                                         Qt::SmoothTransformation));
  waveLabel->setAlignment(Qt::AlignCenter);
  waveLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

  // 添加登录图标
  QLabel *iconLabel = new QLabel(leftWidget);
  QPixmap iconPixmap(
      "/home/ccy/code_workspace/cpp_finall/resource/img/login-mobile.svg");
  iconLabel->setPixmap(
      iconPixmap.scaled(static_cast<int>(leftWidget->width() * 0.6),
                        static_cast<int>(leftWidget->width() * 0.6),
                        Qt::KeepAspectRatio, Qt::SmoothTransformation));
  iconLabel->setAlignment(Qt::AlignCenter);

  leftLayout->addWidget(waveLabel);
  leftLayout->addWidget(iconLabel);
  leftLayout->setStretch(0, 2);
  leftLayout->setStretch(1, 1);
  leftWidget->setStyleSheet("background-color: #4285f4;"); // Google蓝色

  // 右边部分 - 登录表单
  QWidget *rightWidget = new QWidget(centralWidget);
  rightWidget->setStyleSheet("background-color: white;");

  mainLayout = new QVBoxLayout(rightWidget);
  mainLayout->setContentsMargins(40, 40, 40, 40);
  mainLayout->setSpacing(20);

  // 标题和副标题
  titleLabel = new QLabel("欢迎回来", rightWidget);
  titleLabel->setStyleSheet("font-size: 48px; font-weight: bold; color: #333;");
  titleLabel->setAlignment(Qt::AlignLeft);

  subtitleLabel = new QLabel("请登录您的账号", rightWidget);
  subtitleLabel->setStyleSheet("font-size: 32px; color: #666;");
  subtitleLabel->setAlignment(Qt::AlignLeft);

  // 登录表单
  QWidget *formWidget = new QWidget(rightWidget);
  QFormLayout *formLayout = new QFormLayout(formWidget);
  formLayout->setSpacing(15);

  // 用户名输入框
  usernameEdit = new QLineEdit(formWidget);
  usernameEdit->setPlaceholderText("用户名/手机号码");
  usernameEdit->setStyleSheet("QLineEdit { padding: 12px; border: 1px solid "
                              "#ddd; border-radius: 8px; font-size: 28px; }");

  // 为输入框添加图标
  QLabel *userIconLabel = new QLabel(formWidget);
  QPixmap userIcon(
      "/home/ccy/code_workspace/cpp_finall/resource/img/avatar.svg");
  userIconLabel->setPixmap(
      userIcon.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  QHBoxLayout *userLayout = new QHBoxLayout();
  userLayout->addWidget(userIconLabel);
  userLayout->addWidget(usernameEdit);

  // 密码输入框
  passwordEdit = new QLineEdit(formWidget);
  passwordEdit->setPlaceholderText("请输入密码");
  passwordEdit->setEchoMode(QLineEdit::Password);
  passwordEdit->setStyleSheet("QLineEdit { padding: 12px; border: 1px solid "
                              "#ddd; border-radius: 8px; font-size: 28px; }");

  // 为密码框添加图标
  QLabel *lockIconLabel = new QLabel(formWidget);
  QPixmap lockIcon(
      "/home/ccy/code_workspace/cpp_finall/resource/img/authentication.svg");
  lockIconLabel->setPixmap(
      lockIcon.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  QHBoxLayout *passLayout = new QHBoxLayout();
  passLayout->addWidget(lockIconLabel);
  passLayout->addWidget(passwordEdit);

  formLayout->addRow("", userLayout);
  formLayout->addRow("", passLayout);

  // 记住我复选框
  rememberMeCheckbox = new QCheckBox("记住我", formWidget);
  rememberMeCheckbox->setStyleSheet("font-size: 28px; color: #666;");

  // 登录按钮
  loginButton = new QPushButton("登录", rightWidget);
  loginButton->setStyleSheet(
      "QPushButton { background-color: #4285f4; color: white; border: none; "
      "padding: 12px; border-radius: 8px; font-size: 26px; font-weight: bold; "
      "} "
      "QPushButton:hover { background-color: #3367d6; }");
  loginButton->setMinimumHeight(45);

  // 添加阴影效果
  QGraphicsDropShadowEffect *buttonShadow = new QGraphicsDropShadowEffect();
  buttonShadow->setBlurRadius(15);
  buttonShadow->setColor(QColor(66, 133, 244, 80));
  buttonShadow->setOffset(0, 4);
  loginButton->setGraphicsEffect(buttonShadow);

  // 社交媒体登录选项
  QLabel *orLabel = new QLabel("或者使用", rightWidget);
  orLabel->setAlignment(Qt::AlignCenter);
  orLabel->setStyleSheet("color: #999; font-size: 28px;");

  QWidget *socialWidget = new QWidget(rightWidget);
  QHBoxLayout *socialLayout = new QHBoxLayout(socialWidget);
  socialLayout->setAlignment(Qt::AlignCenter);

  QPushButton *googleBtn = new QPushButton(socialWidget);
  QPixmap googleIcon(
      "/home/ccy/code_workspace/cpp_finall/resource/img/google.png");
  googleBtn->setIcon(QIcon(googleIcon));
  googleBtn->setIconSize(QSize(30, 30));
  googleBtn->setFixedSize(50, 50);
  googleBtn->setStyleSheet("QPushButton { background-color: white; border: 1px "
                           "solid #ddd; border-radius: 25px; }");

  QPushButton *fbBtn = new QPushButton(socialWidget);
  QPixmap fbIcon(
      "/home/ccy/code_workspace/cpp_finall/resource/img/facebook.png");
  fbBtn->setIcon(QIcon(fbIcon));
  fbBtn->setIconSize(QSize(30, 30));
  fbBtn->setFixedSize(50, 50);
  fbBtn->setStyleSheet("QPushButton { background-color: white; border: 1px "
                       "solid #ddd; border-radius: 25px; }");

  socialLayout->addWidget(googleBtn);
  socialLayout->addSpacing(20);
  socialLayout->addWidget(fbBtn);

  // 注册按钮与忘记密码按钮布局
  QWidget *bottomWidget = new QWidget(rightWidget);
  QHBoxLayout *bottomLayout = new QHBoxLayout(bottomWidget);

  registerButton = new QPushButton("注册新账号", bottomWidget);
  registerButton->setStyleSheet(
      "QPushButton { background: none; border: none; color: #4285f4; "
      "font-size: 28px; } "
      "QPushButton:hover { color: #3367d6; text-decoration: underline; }");

  bottomLayout->addWidget(registerButton);
  bottomLayout->addStretch();

  // 添加所有组件到主布局
  mainLayout->addWidget(titleLabel);
  mainLayout->addWidget(subtitleLabel);
  mainLayout->addSpacing(20);
  mainLayout->addWidget(formWidget);
  mainLayout->addWidget(rememberMeCheckbox);
  mainLayout->addSpacing(10);
  mainLayout->addWidget(loginButton);
  mainLayout->addSpacing(20);
  mainLayout->addWidget(orLabel);
  mainLayout->addWidget(socialWidget);
  mainLayout->addStretch();
  mainLayout->addWidget(bottomWidget);

  // 将两个面板添加到主布局
  mainHLayout->addWidget(leftWidget);
  mainHLayout->addWidget(rightWidget);

  // 设置窗口样式
  setStyleSheet("font-family: 'Segoe UI', Arial, sans-serif;");
  setAttribute(Qt::WA_TranslucentBackground);
  setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint);
}

void LoginWindow::setupConnections() {
  connect(loginButton, &QPushButton::clicked, this,
          &LoginWindow::onLoginButtonClicked);
  connect(registerButton, &QPushButton::clicked, this,
          &LoginWindow::onRegisterButtonClicked);
}

bool LoginWindow::validateInput() {
  if (usernameEdit->text().isEmpty()) {
    QMessageBox::warning(this, "登录失败", "请输入用户名或手机号码");
    return false;
  }
  if (passwordEdit->text().isEmpty()) {
    QMessageBox::warning(this, "登录失败", "请输入密码");
    return false;
  }
  return true;
}



void LoginWindow::onLoginButtonClicked() {
  if (!validateInput()) {
    return;
  }

  QString username = usernameEdit->text();
  QString password = passwordEdit->text();

  // 登录成功
  bool loginSuccess = false; // 这里应替换为实际的验证结果
  managerSystem::usersManager um;
  std::string user_id = um.getUserIdByName(username.toStdString());

  // 如果用户不存在
  if (user_id.empty()) {
    // 记录失败登录尝试
    tools::Logger::getInstance().log(tools::Logger::LogType::WARNING, "unknown",
                                     "登录失败: 用户名 " +
                                         username.toStdString() + " 不存在");
    QMessageBox::critical(this, "登录失败", "用户名或密码错误");
    return;
  }


  managerSystem::user user(user_id);
  // 检查用户状态是否为banned
  if (user.get_user_status() == "banned") {
    // 记录已禁用用户的登录尝试
    tools::Logger::getInstance().log(tools::Logger::LogType::WARNING, user_id,
                                     "被封禁用户尝试登录: " +
                                         username.toStdString());
    QMessageBox::critical(this, "登录失败",
                          "您的账号已被禁止登录，请联系管理员");
    return;
  }
  qDebug() << "用户ID: manager:1";
  // 验证密码
  if (user.get_user_password() ==
      tools::calculateHash(password.toStdString())) {
    loginSuccess = true;
  }
  qDebug() << "用户ID: manager:2";
  if (loginSuccess) {
    // 记录登录日志
    tools::Logger::getInstance().log(
        tools::Logger::LogType::USER_LOGIN, user_id,
        "用户 " + username.toStdString() + " 登录成功");
    UserChatWindow *userChat =
        new UserChatWindow();
    userChat->setUserId(QString::fromStdString(user_id));
    userChat->setAttribute(Qt::WA_DeleteOnClose);
    userChat->setWindowTitle("用户问答 - " + username);
    userChat->resize(2580, 1600);
    userChat->show();
    close();
  } else {
    // 记录登录失败日志
    tools::Logger::getInstance().log(tools::Logger::LogType::WARNING, user_id,
                                     "登录失败: 用户名 " +
                                         username.toStdString() + " 密码错误");
    QMessageBox::critical(this, "登录失败", "用户名或密码错误");
  }
}

void LoginWindow::onRegisterButtonClicked() {
  RegisterWindow *registerWindow = new RegisterWindow();
  registerWindow->setAttribute(Qt::WA_DeleteOnClose);
  registerWindow->show();
  close();
}

// 实现鼠标事件处理函数，用于支持无边框窗口的拖拽
void LoginWindow::mousePressEvent(QMouseEvent *event) {
  if (event->button() == Qt::LeftButton) {
    isDragging = true;
    dragPosition = event->globalPos() - frameGeometry().topLeft();
    event->accept();
  }
}

void LoginWindow::mouseMoveEvent(QMouseEvent *event) {
  if (event->buttons() & Qt::LeftButton && isDragging) {
    move(event->globalPos() - dragPosition);
    event->accept();
  }
}

void LoginWindow::mouseReleaseEvent(QMouseEvent *event) {
  if (event->button() == Qt::LeftButton) {
    isDragging = false;
    event->accept();
  }
}

// 重写绘制事件以绘制背景图片
void LoginWindow::paintEvent(QPaintEvent *event) {
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing);

  // 绘制背景图片
  if (!backgroundImage.isNull()) {
    // 调整图片大小以适应窗口
    QPixmap scaledImage = backgroundImage.scaled(
        this->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);

    // 添加半透明效果
    QPixmap overlayPixmap(scaledImage.size());
    overlayPixmap.fill(QColor(255, 255, 255, 200));
    QPainter overlayPainter(&scaledImage);
    overlayPainter.setCompositionMode(QPainter::CompositionMode_SourceOver);
    overlayPainter.drawPixmap(0, 0, overlayPixmap);
    overlayPainter.end();

    painter.drawPixmap(0, 0, scaledImage);
  } else {
    // 如果没有背景图片，则填充背景色
    painter.fillRect(rect(), QColor("#f8f8f8"));
  }

  QMainWindow::paintEvent(event);
}